import path from 'path';
import { fileURLToPath } from 'url';
import webpack from 'webpack';
import CompressionPlugin from 'compression-webpack-plugin';
import TerserPlugin from 'terser-webpack-plugin';
import ESLintPlugin from 'eslint-webpack-plugin'; // 替换 require

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const port = process.env.port || process.env.npm_config_port || 80;
const env = process.env.NODE_ENV;
const outputDir =
  env === 'production' ? '机构官网正式环境包' : '机构官网测试环境包';

export default {
  outputDir: outputDir,
  publicPath: process.env.NODE_ENV === 'production' ? '/' : '/',
  productionSourceMap: false,
  devServer: {
    compress: true,
    port: port,
    open: true,
    proxy: {
      '/api': { target: process.env.VUE_APP_API_BASE_URL, changeOrigin: true },
    },
    client: { overlay: false },
    hot: true,
  },

  configureWebpack: {
    resolve: {
      extensions: ['.ts', '.js', '.vue'], // 精简扩展名列表
      alias: { '@': path.resolve(__dirname, 'src') },
    },
    optimization: {
      minimize: true, // 仅在生产环境启用压缩
      usedExports: true, // Tree Shaking
      splitChunks: {
        chunks: 'all',
        minSize: 20000, // 最小模块大小
        maxSize: 250000, // 分割后的最大模块大小
        cacheGroups: {
          vendors: {
            test: /[\\/]node_modules[\\/]/,
            name: 'vendors',
            chunks: 'all',
          },
          common: { name: 'common', minChunks: 2, chunks: 'all' },
        },
      },
      minimizer: [
        new TerserPlugin({
          terserOptions: {
            compress: {
              drop_console: true, // 生产环境才移除 console.log（可选）
              drop_debugger: true, // 移除 debugger
            },
            output: {
              comments: false, // 移除注释
            },
          },
          extractComments: false, // 不将注释提取到单独文件
        }),
      ],
    },
    plugins: [
      new webpack.DefinePlugin({
        __VUE_OPTIONS_API__: JSON.stringify(true),
        __VUE_PROD_DEVTOOLS__: JSON.stringify(false),
        __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: JSON.stringify(false),
      }),
      new CompressionPlugin({
        algorithm: 'gzip', // 可切换为 'brotliCompress'，需要安装 zlib 支持
        test: /\.(js|css|html|svg)$/,
        threshold: 10240, // 大于 10KB 的文件启用压缩
        minRatio: 0.8,
      }),
      new ESLintPlugin({
        extensions: ['jsx', 'tsx', 'js', 'vue', 'ts'],
        emitWarning: true,
        emitError: true,
      }),
    ],
  },
};
